using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

public class LuaBehivour : MonoBehaviour
{
    private LuaEnv luaEnv = Manager.Lua.luaEnv;

    //Lua运行环境
    protected LuaTable luaScriptEnv;

    public string luaName;

    //用于接受lua中方法的委托
    private Action LuaOnInit; 
    private Action LuaUpdate;
    private Action LuaOnDestroy;

    private void Awake()
    {
        luaScriptEnv = luaEnv.NewTable();

        //为每个Lua脚本设置一个独立环境，可在一定程度上防止全局变量或者函数之间的冲突
        LuaTable meta = luaEnv.NewTable();
        meta.Set("__index", luaEnv.Global);
        luaScriptEnv.SetMetaTable(meta);
        meta.Dispose();

        luaScriptEnv.Set("self", this);

        
    }

    private void Update()
    {
        LuaUpdate?.Invoke();
    }

    public virtual void Init(string _luaName)
    {
        luaName = _luaName;

        luaEnv.DoString(Manager.Lua.GetLuaScript(_luaName), _luaName, luaScriptEnv);

        luaScriptEnv.Get("OnInit", out LuaOnInit);
        luaScriptEnv.Get("OnUpdate", out LuaUpdate);

        
    }

    protected virtual void ClearLua()
    {
        LuaOnDestroy = null;
        LuaOnInit = null;
        LuaUpdate = null;

        luaScriptEnv?.Dispose();
        luaScriptEnv = null;
    }

    private void OnDestroy()
    {
        LuaOnDestroy?.Invoke();
        ClearLua();
    }

    private void OnApplicationQuit()
    {
        ClearLua();
    }
}


